﻿using System;
using System.Collections.Generic; 
 
using NUnit.Framework;
using U9API.JsonModel;
using UFIDA.U9.ISV.Customer;
using UFSoft.UBF.Util.Context;
using www.ufida.org.EntityData;
using UFSoft.UBF.Exceptions;

namespace U9API.APIHelper
{
    public class CustomerInfo
    {
        public Int64 ID { get; set; }

        public List<Int64> SiteIds { get; set; }
    }
    public class ICustomerSVHelper : BaseHelper<JsonModel.ApiCustomer>
    {
        public long id;
        public string outmessage;
        //private UFIDA.U9.CBO.Pub.Controller.ContextDTO context;
        private ThreadContext context;
        private www.ufida.org.EntityData.UFIDAU9CBOSCMCustomerCustomerData[] list;
        public CustomerInfo custRes;

        

        protected override void Create(string U9constr, int operation, List<JsonModel.ApiCustomer> models)
        {
            try
            {
                if (models.Count == 0)
                {
                    throw new Exception("JSON不允许为空!");
                } 
                JsonModel.ApiCustomer model = models[0];
                
                UFIDAU9ISVCustomerCustomerDTOData custInfo = new UFIDAU9ISVCustomerCustomerDTOData();
                List<UFIDAU9ISVCustomerCustomerDTOData> custList = new List<UFIDAU9ISVCustomerCustomerDTOData>();
                UFIDAU9ISVCustomerCustomerDTOData[] custs;

                MessageBase[] returnMsg;

                #region  客户1

                UFIDAU9CBOPubControllerCommonArchiveDataDTOData m_org = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                m_org.m_code = model.OrgCode;

                UFIDAU9CBOPubControllerCommonArchiveDataDTOData m_saleser = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                m_saleser.m_code = model.Saleser;//产业链部门销售业务员 

                UFIDAU9BasePropertyTypesEffectiveData m_effective = new UFIDAU9BasePropertyTypesEffectiveData();
                m_effective.m_effectiveDate = Convert.ToDateTime(model.Effective_EffectiveDate);// DateTime.Now;
                m_effective.m_disableDate = new DateTime(9999, 12, 31);
                m_effective.m_isEffective = true;

                UFIDAU9CBOPubControllerCommonArchiveDataDTOData m_currency = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData();
                m_currency.m_code = "C001";//人民币
                custInfo.m_iD = model.ID;
                custInfo.m_code = model.Code;
                custInfo.Name = model.Name;
                custInfo.m_shortName = model.ShortName;
                custInfo.m_org = m_org;
                custInfo.m_saleser = m_saleser;
                custInfo.m_effective = m_effective;
                custInfo.m_priceListID = model.SalePriceList;
                custInfo.m_customerCategory = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData() { m_code = model.CustomerCategory };
                 

                custInfo.m_isPriceListModify = model.isPriceListModify; //价目表可改
                custInfo.m_isShipmentModify = model.isShipmentModify;  // 出货原则可改
                custInfo.m_isRecTermModify = model.isRecTermModify;    // 收款条件可改
                custInfo.m_isARCfmModify = model.isARCfmModify;    //立账条件可改
                custInfo.m_isCreditCheck = model.isCreditCheck;//信用检查

                custInfo.m_territory = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData() { m_code = model.Territory };
                custInfo.m_tradeCategory = model.TradeCategory;
                custInfo.m_saleType = model.SaleType;

                custInfo.m_descFlexField = new UFIDAU9BaseFlexFieldDescFlexFieldDescFlexSegmentsData() { m_privateDescSeg1 = model.DescFlexField_PrivateDescSeg1_ID };
                custInfo.m_taxSchedule = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData() { m_code = model.TaxSchedule };
                custInfo.m_shippmentRule = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData() { m_code = model.ShippmentRule };
                custInfo.m_returnTerm = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData() { m_code = model.ReturnTerm };
                custInfo.m_invoiceVerificationOrder = model.InvoiceVerificationOrder;
                custInfo.m_verificationMode = model.VerificationMode;
                custInfo.m_recervalTerm = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData() { m_code = model.RecervalTerm };
                custInfo.m_aRConfirmTerm = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData() { m_code = model.ARConfirmTerm };
                custInfo.m_department = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData() { m_code = model.Department };
                custInfo.m_state = model.State;
                custInfo.m_supplyOrg = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData() { m_code = model.SupplyOrg };
                custInfo.m_demandTransType = model.DemandTransType;
                custInfo.m_supplySource = model.SupplySource;
                

                custInfo.m_commissionType = 0;  //佣金方式：0 固定金额
                custInfo.m_commission = 100m;
                custInfo.m_commissionCurrency = m_currency;
                //交易币种
                custInfo.m_tradeCurrency = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData() { m_code = "C001" };
                //收款币种
                custInfo.m_payCurrency = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData() { m_code = "C001" };

                //add 240921 StateTaxNo
                custInfo.m_stateTaxNo = model.StateTaxNo;   //国税号
                custInfo.m_districtTaxNo = model.DistrictTaxNo; //地税号
                custInfo.CorpUnifyCode = model.CorpUnifyCode;   //工商注册号

                #region  客户位置


                List<UFIDAU9ISVCustomerCustomerSiteDTOData> custSiteList = new List<UFIDAU9ISVCustomerCustomerSiteDTOData>();
                UFIDAU9ISVCustomerCustomerSiteDTOData[] custSites1;
                foreach (var item in model.Sites)
                {
                    UFIDAU9ISVCustomerCustomerSiteDTOData custSiteInfo = new UFIDAU9ISVCustomerCustomerSiteDTOData();
                    
                    custSiteInfo.m_iD = item.ID;
                    if (item.ID > 0)
                    {
                        custSiteInfo.m_operateType = 1;
                    }
                    else
                    {
                        custSiteInfo.m_operateType = 0;
                    }
                    custSiteInfo.m_code = item.Code;
                    custSiteInfo.Name = item.Name;
                    custSiteInfo.m_isPriceListModify = item.isPriceListModify;
                    custSiteInfo.m_isShippmentRuleEditable = item.isShippmentRuleEditable;
                    custSiteInfo.m_isPaymentTermEditable = item.isPaymentTermEditable;
                    custSiteInfo.m_effective = new UFIDAU9BasePropertyTypesEffectiveData();
                    custSiteInfo.m_effective.m_isEffective = true;
                    if (!string.IsNullOrEmpty(item.Effective_EffectiveDate))
                    {
                        custSiteInfo.m_effective.m_effectiveDate = Convert.ToDateTime(item.Effective_EffectiveDate);
                    }
                    if (!string.IsNullOrEmpty(item.Effective_DisableDate))
                    {
                        custSiteInfo.m_effective.m_disableDate = Convert.ToDateTime(item.Effective_DisableDate);
                    }
                    if (!string.IsNullOrEmpty(model.Territory))
                    {
                        custSiteInfo.m_territory = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData() { m_code = item.Territory };
                    }
                     

                    //custSiteInfo.m_officeSite = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData(){ m_code = item.OfficeSite};
                    if (!string.IsNullOrEmpty(item.RegisterAddress))
                    {
                        custSiteInfo.m_registerAddress = new UFIDAU9CBOPubControllerCommonArchiveDataDTOData() { m_name = item.RegisterAddress };
                    }
                    custSiteInfo.m_isBillTo = item.isBillTo;
                    custSiteInfo.m_isClaim = item.isClaim;
                    custSiteInfo.m_isContrast = item.isContrast;
                    custSiteInfo.m_isShipTo = item.isShipTo;
                    custSiteInfo.m_isPayment = item.isPayment;
                    custSiteInfo.m_isDefaultBillTo = item.isDefaultBillTo;
                    custSiteInfo.m_isDefaultClaim = item.isDefaultClaim;
                    custSiteInfo.m_isDefaultContrast = item.isDefaultContrast;
                    custSiteInfo.m_isDefaultShipTo = item.isDefaultShipTo;
                    custSiteInfo.m_isDefaultPayment = item.isDefaultPayment;

                    custSiteList.Add(custSiteInfo);
                }
                
                custSites1 = custSiteList.ToArray();
                #endregion

                custInfo.m_customerSiteDTOs = custSites1;

                custList.Add(custInfo);
                #endregion 


                custs = custList.ToArray();

                context = CreateContextObj();

                if (operation == 0)
                {
                    UFIDAU9ISVCustomerIBatchCreateCustomerByDTOSVClient proxy = new UFIDAU9ISVCustomerIBatchCreateCustomerByDTOSVClient();
                    list = proxy.Do(context, custs, null, out returnMsg);
                    //outmessage = string.Concat("", returnMsg);
                    Pub.WriteLog.WriteLine("批量创建客户成功：" + outmessage);
                    custRes = new CustomerInfo();
                    if (list.Length > 0)
                    {
                        custRes.ID = list[0].m_iD;
                        custRes.SiteIds = new List<long>();
                        foreach (var item in list[0].m_customerSites)
                        {
                            custRes.SiteIds.Add(item.m_iD);
                        }
                    }
                }

                if (operation == 1)
                {
                    UFIDAU9ISVCustomerIBatchModifyCustomerByDTOSVClient proxy = new UFIDAU9ISVCustomerIBatchModifyCustomerByDTOSVClient();
                    list = proxy.Do(context, custs, null, out returnMsg);
                    //outmessage = string.Concat("",returnMsg);
                    Pub.WriteLog.WriteLine("批量修改客户完成：" + outmessage);
                    custRes = new CustomerInfo();
                    if (list.Length > 0)
                    {
                        custRes.ID = list[0].m_iD;
                        custRes.SiteIds = new List<long>();
                        foreach (var item in list[0].m_customerSites)
                        {
                            custRes.SiteIds.Add(item.m_iD);
                        }
                    }
                }  
            }
            catch (System.Exception err)
            {
                if (err is System.ServiceModel.FaultException<UFSoft.UBF.Service.ServiceException>)
                {
                    Pub.WriteLog.WriteLine((((System.ServiceModel.FaultException<UFSoft.UBF.Service.ServiceException>)(err)).Detail).StackTrace);
                    //Pub.WriteLog.WriteLine((((System.ServiceModel.FaultException<UFSoft.UBF.Service.ServiceException>)(err)).Detail).Message);
                    outmessage = (((System.ServiceModel.FaultException<UFSoft.UBF.Service.ServiceException>)(err)).Detail).Message;
                }
                else
                {
                    Pub.WriteLog.WriteLine(err.StackTrace); //堆栈段异常
                    outmessage = err.Message;  //异常信息
                }

                //Pub.WriteLog.WriteLine(outmessage);
                throw new Exception(outmessage);
            }
        }

     
         
        private static ThreadContext CreateContextObj()
        {
            //context = new UFIDA.U9.CBO.Pub.Controller.ContextDTO();
            //context.EntCode = "01"; 
            //context.UserID = 1002311230116358;
            //context.OrgID = 1001510141244049;  
            //context.CultureName = "zh-CN";
            //context.WriteToContext();

            //实例化应用上下文对象
            ThreadContext  context = new ThreadContext();

            context.nameValueHas = new Dictionary<object, object>();
            context.nameValueHas.Add("OrgID", "1001510141244049");//code=All001
            context.nameValueHas.Add("UserID", "1002311230116358");//code=API001
            context.nameValueHas.Add("EnterpriseID", "01");//系统管理平台里的代码
            context.nameValueHas.Add("DefaultCultureName", "zh_CN");
            context.nameValueHas.Add("CultureName", "zh-CN");
            context.nameValueHas.Add("EnterpriseName", "01");
            context.nameValueHas.Add("Support_CultureNameList", "zh_CN");
            return context;
        }
    }
}

